﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLCMS.Business.DwzFrame;
using ZLCMS.Data.Common;
using ZLCMS.Data.Model;
using ZLCMS.Business;
using NHibernate;
using ZLCMS.Business.Util;
using Newtonsoft.Json;
using ZLCMS.Business.UploadFileInfo;

namespace ZLCMS.Web.SystemManage.Template.Web
{
    public partial class DocDetail : System.Web.UI.Page
    {
        protected FrameHelper _framePage;

        protected CmsKindInfo _kindDB;

        protected CmsDocConfig _config;

        protected void Page_Load(object sender, EventArgs e)
        {
            //初始化DWZ控件
            _framePage = new FrameHelper(this);

            if (!IsPostBack)
            {
                //初始化控件值
                InitializeContent();
            }
            else {
                SaveDoc();
            }
        }

        protected void InitializeContent()
        {
            //页面控件值
            if (!IsPostBack)
            {
                using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
                {
                    try
                    {
                        int uid = 0;// Request["uid"];
                        int tempid = Int32.Parse(Request["tempid"]);
                        CmsUserTemplatePage upage = session.Get<CmsUserTemplatePage>(tempid);
                        string kind = upage.DocKind;
                        if (Request["src"] == "man")//内容文章
                        {
                            CmsUserTemplateDoc tdoc =
                                session.CreateQuery("from CmsUserTemplateDoc where UserAccount=:code and UserTemplatePagesId=:tempid")
                                .SetParameter("code", UserKit.GetUserAccountWithoutException())
                                .SetParameter("tempid", tempid)
                                .UniqueResult<CmsUserTemplateDoc>();
                            if (tdoc != null)
                            {
                                uid = tdoc.DocId;
                            }
                        }
                        else//列表文章
                        {
                            if (!string.IsNullOrEmpty(Request["uid"]))
                            {
                                try
                                {
                                    uid = Int32.Parse(Request["uid"]);
                                }
                                catch 
                                {
                            	
                                }
                            }
                        }
                        CmsDocInfo doc = session.Get<CmsDocInfo>(uid);
                        if (doc != null && doc.OwnerAccount == UserKit.GetUserAccountWithoutException())
                        {
                            CmsTreeDef node = null;
                            if (doc.TypeId != 0)
                            {
                                node = session.Get<CmsTreeDef>((int)doc.TypeId);
                            }
                            if (node != null)
                            {
                                ddTreeControl.SelectedNodeId = node.Id;
                                ddTreeControl.SelectedNodeText = node.Name;
                            }

                            txtTitle.Text = doc.Title;
                            txtName.Text = doc.Name;
                            txtWriter.Text = doc.Author;

                            txtContent.Value = doc.Content;
                            txtSummary.Value = doc.Summary;

                            txtUrl.Text = doc.Url;
                            chkRcmd.Checked = DatabaseHelper.IsTrue(doc.IsRecommend);
                            chkHot.Checked = DatabaseHelper.IsTrue(doc.IsHot);
                            tb_order.Text = doc.ShowOrder.ToString();

                            fc_imgurl.Value = doc.ThumbnailUrl;
                            fc_fileurl.Value = doc.AttachmentUrl;

                            txtWebTitle.Text = doc.WebTitle;
                            txtKeyword.Text = doc.WebKeyword;
                            txtDesc.Text = doc.WebDesc;

                            tb_cdate.Text = doc.CreateDate.ToString("yyyy-MM-dd");
                        }
                        else
                        {
                            tb_cdate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                        }


                        _kindDB = session.Get<CmsKindInfo>(kind);
                        _config = session.Get<CmsDocConfig>(_kindDB.ConfigId);


                        fc_fileurl.FileFilters = _config.FileType;



                        try
                        {
                            UploadConfig cfg = JsonConvert.DeserializeObject<UploadConfig>(_kindDB.ExtendJasonContent);
                            fc_fileurl.Config = cfg;
                            fc_imgurl.Config = cfg;
                        }
                        catch { }

                        ViewState["uid"] = uid;
                        ViewState["tempid"] = tempid;
                        ViewState["kind"] = kind;
                    }
                    catch (System.Exception ex)
                    {
                        _framePage.Alert(new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.Message });
                    }
                }
            }
        }


        /// <summary>
        /// 保存数据库
        /// </summary>
        protected void SaveDoc()
        {
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                CmsDocInfo doc = session.Get<CmsDocInfo>(ViewState["uid"]);
                if (doc == null)
                {
                    doc = new CmsDocInfo();
                    doc.OwnerAccount = UserKit.GetUserAccountWithoutException();

                }

                if (ddTreeControl.SelectedNodeId == -1)
                {
                    try
                    {
                        doc.TypeId = Convert.ToInt32(ViewState["typeid"]);
                    }
                    catch 
                    {
                    	
                    }
                }
                else
                {
                    doc.TypeId = ddTreeControl.SelectedNodeId;
                }

                doc.Title = txtTitle.Text;
                doc.Name = txtName.Text;
                doc.Author = txtWriter.Text;

                doc.Summary = txtSummary.Value;
                doc.Content = txtContent.Value;

                doc.Url = txtUrl.Text;
                doc.ThumbnailUrl = fc_imgurl.Value;
                doc.AttachmentUrl = fc_fileurl.Value;
                doc.IsHot = DatabaseHelper.ConvertBool(chkHot.Checked);
                doc.IsRecommend = DatabaseHelper.ConvertBool(chkRcmd.Checked);
                doc.ShowOrder = int.Parse(tb_order.Text);

                doc.WebTitle = txtWebTitle.Text;
                doc.WebKeyword = txtKeyword.Text;
                doc.WebDesc = txtDesc.Text;

                doc.CreateDate = DateTime.Parse(tb_cdate.Text + " 00:00:00");
                doc.UpdateDate = DateTime.Now;
                doc.Kind = ViewState["kind"] as string;
                session.SaveOrUpdate(doc);


                CmsUserTemplateDoc tdoc =
                    session.CreateQuery("from CmsUserTemplateDoc where UserAccount=:code and DocId=:uid")
                    .SetParameter("code", UserKit.GetUserAccountWithoutException())
                    .SetParameter("uid", doc.Id)
                    .UniqueResult<CmsUserTemplateDoc>();
                if (tdoc == null)
                {
                    tdoc = new CmsUserTemplateDoc();
                    tdoc.DocId = doc.Id;
                    tdoc.UserAccount = UserKit.GetUserAccountWithoutException();
                    tdoc.UserTemplatePagesId = (int)ViewState["tempid"];
                    session.Save(tdoc);
                }


                session.Flush();

                ReturnCode rc = new ReturnCode()
                {
                    statusCode = 200,
                    message = "操作成功!"
                };


                rc.callbackType = "forward";
                rc.forwardUrl = "/SystemManage/Template/Web/DocDetail.aspx?Kind=" + doc.Kind + 
                    "&tabid=DocDetail&tempid=" + ViewState["tempid"] + "&uid=" + doc.Id;
                
                _framePage.Alert(rc);
            }
        }
    }
}
